# -*- coding: utf-8 -*-
from datetime import datetime
import time, random
from controller.standard_ai_data import ai_data_standardization
from service.person import person_data, person_name
from service.next import next_person
from service.say import say_hello
from model.robot_history_model import RobotHistoryModel
from model.user_model import UserModel
# from model.thread import WorkerThread
from service.open_chrome import open_windows
from service.recommend import to_recommend
from service.iframes import to_iframe, iframe_sift


z_id = "123456"  # 登录账号名称
a = '''1.负责全面管理CRM客户系统的日常运维工作，确保系统稳定运行并持续优化用户体验。通过定期的性能评估、故障排查与功能升级，不断提升系统的响应速度与数据准确性，为公司客户关系管理提供坚实的技术支持。
2.针对TikTok、Shopee、Lazada等热门跨境电商平台，负责主导ERP管理系统的开发工作。通过深入研究各平台API与业务流程，我设计并实现高效的数据对接方案，实现订单、库存、物流等信息的自动化处理与同步。不断优化系统架构与功能模块，以满足公司跨境电商业务快速发展的需求，提升运营效率与竞争力。
3.全面负责从系统设计、开发、维护到上线、运营、迭代的整个生命周期管理。在系统设计阶段，注重需求分析与架构设计，确保系统既满足当前业务需求又具备可扩展性；在系统上线后，持续关注系统运行状态，进行必要的维护与优化工作，确保系统稳定运行并不断提升用户体验。
离职原因:团队解散'''


class Browser:
    """浏览器操作类"""

    def __init__(self, conditions):
        """
        初始化
        :param conditions: 条件列表
        """
        self.conditions = conditions
        self.sum = conditions[0]
        self.browser = open_windows()
        print("浏览器打开成功")
        self.manage()

    def time_expand(self, data):
        """
        随机延长时间
        :param data: 列表[3.0, 7.0]
        :return:
        """
        random_float = random.uniform(data[0], data[1])
        time.sleep(random_float)

    def time_conform(self):
        """
        运行时间
        :param :
        :return:
        """
        # 判断运行时间
        time_now = int((time.time() * 1000))

        time_convert1 = self.conditions[1]
        time_convert2 = self.conditions[2]
        time_convert3 = self.conditions[3]
        # if (time_convert3 is not None) and (time_convert2 is not None) and (time_convert1 is not None):
        #     if (time_convert1[0] < time_now < time_convert1[-1]) or (time_convert2[0] < time_now < time_convert2[-1]) or (time_convert3[0] < time_now < time_convert3[-1]):
        #         return True
        #     else:
        #         return False
        if time_convert3:
            if (time_convert1[0] < time_now < time_convert1[-1]) or (time_convert2[0] < time_now < time_convert2[-1]) or (time_convert3[0] < time_now < time_convert3[-1]):
                return True
            else:
                return False

        elif time_convert2:
            if (time_convert1[0] < time_now < time_convert1[-1]) or (time_convert2[0] < time_now < time_convert2[-1]):
                return True
            else:
                return False
        elif time_convert1:
            if time_convert1[0] < time_now < time_convert1[-1]:
                return True
            else:
                return False
        else:
            return True

    def manage(self):
        """
        浏览器操作主程序
        :return:
        """
        print("开始运行")
        # 判断运行时间
        is_times = self.time_conform()
        if not is_times:
            return

        # 检查是否强制停止
        t = is_start(z_id)
        if not t:
            return

        # 点击推荐人
        print("点击推荐人")
        self.time_expand([2.0, 5.0])
        to_recommend(self.browser)
        self.time_expand([1.0, 3.0])

        # 切换iframe
        print("切换iframe")
        driver = to_iframe(self.browser)
        self.browser.switch_to.frame(driver)
        if not driver:
            raise Exception("切换iframe失败")

        # 筛选简历条件
        self.time_expand([1.0, 2.0])
        iframe_sift(self.browser)
        self.time_expand([2.0, 5.0])

        # 检查是否强制停止
        t = is_start(z_id)
        if not t:
            return

        # 获取单个用户信息
        person_name(self.browser)
        self.time_expand([2.0, 5.0])

        # 打招呼总数
        for row in range(self.sum):
            # 获取用户工作经历
            person_datas = person_data(self.browser)
            per = RobotHistoryModel(None, z_id, 0, person_datas, datetime.now())
            per.save()
            self.time_expand([2.0, 5.0])

            # 检查是否强制停止
            t = is_start(z_id)
            if not t:
                return

            # 提交ai机器人
            self.time_expand([2.0, 5.0])
            is_accord = ai_data_standardization(person_datas)  # True: 符合要求, False: 不符合要求
            per = RobotHistoryModel(None, z_id, 1, '', datetime.now())
            per.save()
            if is_accord:
                self.time_expand([5.0, 12.0])
                say_hello(self.browser)
                self.time_expand([3.0, 5.0])
                next_person(self.browser)
                per = RobotHistoryModel(None, z_id, 2, '', datetime.now())
                per.save()
            else:
                self.time_expand([5.0, 12.0])
                next_person(self.browser)

        print("完成!!!")


def is_start(z_id):
    """
    判断用户状态是否为开始状态
    :param z_id: 用户名
    :return:
    """
    state = UserModel.get_user_by_states(z_id)
    # 检查状态
    if state:
        for row in state:
            if getattr(row, 'states') == 0:
                # 停止状态
                return False
            else:
                # 启动状态

                return True

    else:
        return False


# def mains(conditions):
#     """点击启动
#     :param conditions: 筛选条件
#     :return:
#     """
#     '''
#     点击启动按钮——>判断选数据状态栏是否符合要求——>更新数据库状态栏——>启动浏览器——>登录——>.....
#     '''
#     # 更新数据库状态栏
#
#     # 多线程创建
#     thread_start = WorkerThread(1, conditions)  # 创建task_one的线程
#     thread_start.start()  # 启动线程


if __name__ == '__main__':

    bw = Browser([3, '', '', '', 0])


